import { reactive } from 'vue'

// 简单的响应式状态管理
export const store = reactive({
  // 用户状态
  user: {
    isLogin: false,
    userInfo: null
  },
  
  // 购物车状态
  cart: {
    items: [],
    total: 0
  },
  
  // 购物车方法
  addToCart(product) {
    const existingItem = this.cart.items.find(item => item.id === product.id)
    
    if (existingItem) {
      existingItem.quantity += 1
    } else {
      this.cart.items.push({
        ...product,
        quantity: 1
      })
    }
    
    this.updateCartTotal()
  },
  
  removeFromCart(productId) {
    const index = this.cart.items.findIndex(item => item.id === productId)
    if (index > -1) {
      this.cart.items.splice(index, 1)
      this.updateCartTotal()
    }
  },
  
  updateQuantity(productId, quantity) {
    const item = this.cart.items.find(item => item.id === productId)
    if (item) {
      if (quantity <= 0) {
        this.removeFromCart(productId)
      } else {
        item.quantity = quantity
        this.updateCartTotal()
      }
    }
  },
  
  clearCart() {
    this.cart.items = []
    this.cart.total = 0
  },
  
  updateCartTotal() {
    this.cart.total = this.cart.items.reduce((total, item) => {
      return total + (item.price * item.quantity)
    }, 0)
  },
  
  getCartItemCount() {
    return this.cart.items.reduce((count, item) => count + item.quantity, 0)
  },

  // 用户认证方法
  login(userInfo, remember = false) {
    this.user.isLogin = true
    this.user.userInfo = userInfo
    
    // 保存到localStorage
    const authData = { userInfo, remember }
    localStorage.setItem('authData', JSON.stringify(authData))
    
    if (remember) {
      // 记住登录状态，设置较长的过期时间
      const expireTime = Date.now() + (30 * 24 * 60 * 60 * 1000) // 30天
      localStorage.setItem('authExpire', expireTime.toString())
    } else {
      // 不记住登录状态，关闭浏览器后过期
      sessionStorage.setItem('authSession', 'true')
    }
  },

  logout() {
    this.user.isLogin = false
    this.user.userInfo = null
    
    // 清除存储
    localStorage.removeItem('authData')
    localStorage.removeItem('authExpire')
    sessionStorage.removeItem('authSession')
  },

  // 检查登录状态
  checkAuth() {
    try {
      const authData = JSON.parse(localStorage.getItem('authData') || 'null')
      if (!authData) return false

      const expireTime = localStorage.getItem('authExpire')
      const sessionAuth = sessionStorage.getItem('authSession')
      
      // 检查是否过期
      if (expireTime) {
        if (Date.now() > parseInt(expireTime)) {
          this.logout()
          return false
        }
      } else if (!sessionAuth) {
        this.logout()
        return false
      }

      // 恢复登录状态
      this.user.isLogin = true
      this.user.userInfo = authData.userInfo
      return true
    } catch (error) {
      console.error('检查登录状态失败:', error)
      this.logout()
      return false
    }
  },

  // 更新用户信息
  updateUserInfo(newUserInfo) {
    if (this.user.isLogin && this.user.userInfo) {
      this.user.userInfo = { ...this.user.userInfo, ...newUserInfo }
      
      // 更新localStorage中的数据
      const authData = JSON.parse(localStorage.getItem('authData') || '{}')
      authData.userInfo = this.user.userInfo
      localStorage.setItem('authData', JSON.stringify(authData))
    }
  }
})
